package com.supinfo.food.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import com.supinfo.food.dao.DishDao;
import com.supinfo.food.entities.Dish;

/**
 * Dish DAO 
 * @author Syn
 */
public class JpaDishDao implements DishDao{

	/** Entity manager */
	private EntityManager entityManager;

	public JpaDishDao() {
		entityManager = ManagerDAO.getEntityManager();
	}
	
	@Override
	public Dish addDish(Dish dish) {
		entityManager.getTransaction().begin();
		entityManager.persist(dish);
		entityManager.getTransaction().commit();
		return dish; //--Patch Nico il faut retourner le dish nan?
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Dish> getAllDishes() {
		return entityManager.createQuery("SELECT d FROM Dish d").getResultList();
	}

	@Override
	public void removeDish(Dish dish) {
		entityManager.getTransaction().begin();
		entityManager.remove(dish);
		entityManager.getTransaction().commit();
	}

	@Override
	public Dish updateDish(Dish dish) {
		entityManager.getTransaction().begin();
		entityManager.merge(dish);
		entityManager.getTransaction().commit();
		return dish;
	}

	@Override
	public Dish findDish(Long id) {
		try {
			return entityManager.find(Dish.class, id);
		} catch (NoResultException e) {
			return null;
		}
	}
	
	@Override
	public void delete(Long id) {
		Dish dish = findDish(id);
		if (dish != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(dish);
			entityManager.getTransaction().commit();
		}
	}
	
}
